package com.yong.es.pinyin.service;

import com.alibaba.fastjson.JSON;
import com.sun.org.apache.xpath.internal.operations.Bool;
import com.yong.es.pinyin.constant.Constants;
import com.yong.es.pinyin.jopo.Course;
import com.yong.es.pinyin.repository.CourseRepository;
import org.apache.lucene.analysis.Analyzer;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.ml.dataframe.Classification;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.analysis.Analysis;
import org.elasticsearch.index.mapper.IpFieldMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CourseService {
    @Resource
    private CourseRepository courseRepository;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    public Boolean cacheData() {
        // 首先判断是否存在索引
        if (!this.exists()) {
            this.createIndex();
        }

        List<Course> all = courseRepository.findAll();
        BulkRequest request = new BulkRequest();
        request.timeout("120s");
        for (Course course : all) {
            request.add(new IndexRequest(Constants.INDEX_NAME)
                    .source(JSON.toJSONString(course), XContentType.JSON));
        }
        try {
            BulkResponse bulk = restHighLevelClient.bulk(request, RequestOptions.DEFAULT);
            return !bulk.hasFailures();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean exists() {
        try {
            GetIndexRequest request = new GetIndexRequest(Constants.INDEX_NAME);
            return restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean deleteIndex(){
        try {
            DeleteIndexRequest request = new DeleteIndexRequest(Constants.INDEX_NAME);
            AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
            return delete.isAcknowledged();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean createIndex() {
        CreateIndexRequest request = new CreateIndexRequest(Constants.INDEX_NAME);

        try {
            XContentBuilder settingsBuilder = XContentFactory.jsonBuilder()
                    .startObject()
                    .startObject("analysis")
                    .startObject("analyzer")
                    .startObject("pinyin_analyzer").field("tokenizer", "my_pinyin").endObject()
                    .endObject()
                    .startObject("tokenizer")
                    .startObject("my_pinyin")
                    .field("type", "pinyin")
                    .field("keep_separate_first_letter", "false")
                    .field("keep_full_pinyin", "true")
                    .field("keep_original", "true")
                    .field("limit_first_letter_length", "16")
                    .field("lowercase", "true")
                    .field("remove_duplicated_term", "true")
                    .endObject()
                    .endObject()
                    .endObject()
                    .endObject();
            request.settings(settingsBuilder);


            CreateIndexResponse response = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
            System.out.println(response);
            //return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        //return false;
        IndexOperations indexOps = elasticsearchRestTemplate.indexOps(Course.class);
        indexOps.createMapping(Course.class);
        indexOps.putMapping(Course.class);
        return true;
    }
}
